package JavaSEAdvance.day06_Date.D607_HomeWork;

import javax.swing.text.DateFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Scanner;

/**
 * @author Xiao
 * @date 2021/7/22
 */
public class Test04 {
    /**
     * 4. 用两种方式实现：键盘录你的入生日 (xxxx-xx-xx)  计算你活了多少天？
     */
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        LocalDate date = null;
        String s = null;
        while (true) {
            System.out.println("请输入你的生日（如：2001-01-01）：");
            s = sc.nextLine();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            try {
                date = LocalDate.parse(s, formatter);
            } catch (DateTimeParseException e) {
                System.out.println("您输入的生日格式有误，请按照给定的格式输入生日。");
                continue;
            }
            break;
        }
        LocalDate now = LocalDate.now();
        Period p = Period.between(date, now);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String s1 = now.format(formatter);
        System.out.println("截止到" + s1);
        System.out.println("你活了" + p.getYears() + "年零" + p.getMonths() + "个月零" + p.getDays() + "天");
        System.out.println("共计" + p.toTotalMonths() + "个月");
        System.out.println("----------");
        Period until = date.until(now);
        System.out.println(until);  //P20Y6M21D
        System.out.println("----------");
       /* //UnsupportedTemporalTypeException
        String str = s + " 00:00:00";
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime date1 = LocalDateTime.parse(str,formatter1);
        LocalDateTime date2 = LocalDateTime.now();
        Duration d = Duration.between(date1, date2);
        long days = d.toDays();
        System.out.println("截止到" + s);
        System.out.println("你活了" + days + "天");
        System.out.println("---------");*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(s);
        Date d2 = new Date();
        long time1 = d1.getTime();
        long time2 = d2.getTime();
        System.out.println("共计" + (time2 - time1)/24/3600/1000 + "天。");
    }
}
